//
//  BaseAdapter.swift
//  OneDay
//
//  Created by cheng xi on 2016/10/15.
//  Copyright © 2016年 xicheng. All rights reserved.
//

import UIKit


public class BaseAdapter<MODEL:Any,CELL:UITableViewCell,TARGET_VC:TXBaseViewController>:NSObject,UITableViewDelegate,UITableViewDataSource {
  
  
  internal weak var tableView: UITableView? = nil
  internal var dataList: [MODEL]? = nil
  internal var cellIdentifier: String! = nil
  internal weak var targetVC:TARGET_VC? = nil
  
  internal var isEmpty: Bool {
    get {
      return dataList == nil || dataList!.count == 0
    }
  }
  
  convenience init(vc: TARGET_VC) {
    self.init()
    self.targetVC = vc
  }
  
  private func setupTableView(tableView: UITableView, cellIdentifier: String) {
    self.tableView = tableView
    self.cellIdentifier = cellIdentifier
    self.tableView?.delegate = self
    self.tableView?.dataSource = self
    self.tableView?.register(CELL.self, forCellReuseIdentifier: cellIdentifier)
    self.tableView?.separatorStyle = .none
  }
  
  public func setupTableView(tableView: UITableView){
    
    self.setupTableView(tableView: tableView, cellIdentifier: "\(tx_className())_\(TagIdGenerator.sharedInstance.generatorTagId())")
  }
  
  public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
    let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! CELL
    
    setupCell(tableView,cell: cell, model: dataList![indexPath.row], indexPath: indexPath )
    return cell
  }
  
  public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    
  }
  
  public func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
    return false
  }
  
  public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    fatalError("需要复写heightForRowAt")
  }
  
  
  func setupCell(_ tableView:UITableView, cell: CELL, model: MODEL, indexPath: IndexPath) {
    fatalError("需要复写setupCell")
  }
  
  
  public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    
    let count = dataList == nil ? 0 : dataList!.count
    return count
  }
  
  
  func refreshCount(listData:[MODEL]?){
    self.dataList?.removeAll()
    self.dataList = listData
    self.tableView?.reloadData()
  }
  
  
  public func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return false
  }
  
  public func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
    return .delete
  }
  
  public func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {    
    return nil
  }
  
}

typealias AdapterLoadNextListener = (( _ index: Int,_ page:Int) -> Void)

public class BaseListTableViewAdapter<MODEL:Any,CELL:UITableViewCell,TARGET_VC:TXBaseViewController>:BaseAdapter<MODEL,CELL,TARGET_VC>{
  
  private var currentPageIndex: Int = 0
  
  private var rowTotal:Int = 0
  
  internal var pageSize:Int = 0
  
  private var currentEndRowIndex = 0
  
  private var _loadpageIndexContainer:[Int] = [Int]()
  
  
  internal var loadNextListener: AdapterLoadNextListener? = nil {
    didSet {
      
      guard let _ = loadNextListener else {
        return
      }
      
      tableView?.tx_addLoadMoreListener {
        [unowned self] in
        guard let listener = self.loadNextListener else {
          return
        }
        listener(self.currentPageIndex + 1,self.pageSize)
      }
    }
  }
  
  internal var refreshListener: (() -> Void)? = nil {
    
    didSet {
      guard let _ = refreshListener else {
        return
      }
      tableView?.tx_addRefreshListener {
        [unowned self] in
        guard let listener = self.refreshListener else {
          return
        }
        listener()
      }
    }
  }
  
  internal var hasNextFlag: Bool = true {
    didSet {
      changeFootStatus(hasNext: hasNextFlag, currentPage: currentPageIndex)
    }
  }
  
  
  func refreshCount(baseListModel:BaseListModel<MODEL>?){
    guard let baseListModel = baseListModel else {
      self.dataList?.removeAll()
      self.tableView?.reloadData()
      return
    }
    
    self.dataList?.removeAll()
    self.dataList = baseListModel.dataList
    self.configBaseListModel(baseListModel: baseListModel)
    self.tableView?.reloadData()
    self.hasNextFlag = self.currentEndRowIndex < self.rowTotal
  }
  
  func addLoadData(baseListModel:BaseListModel<MODEL>?) {
    guard let baseListModel = baseListModel else {
      return
    }
    if currentPageIndex != baseListModel.pageIndex {
      self.configBaseListModel(baseListModel: baseListModel)
      self.dataList!.append(contentsOf: baseListModel.dataList!)
      self.tableView?.reloadData()
      self.hasNextFlag = self.currentEndRowIndex < self.rowTotal
    }
  }
  
  
  private func configBaseListModel(baseListModel:BaseListModel<MODEL>){
    self.currentPageIndex = baseListModel.pageIndex
    self.pageSize = baseListModel.pageSize
    self.currentEndRowIndex = baseListModel.endRowIndex
    self.rowTotal = baseListModel.rowTotal
  }
  
  func changeFootStatus(hasNext: Bool, currentPage: Int) {
    
    guard let tableView = tableView else {
      return
    }
    
    if hasNext {
      tableView.tx_refreshStatus = .normal
    }else {
      if let count = self.dataList?.count {
        tableView.tx_setNoMoreData(needHidden: count < 20)
      }
    }
  }
  
  
  
}

